import React, { FC, useEffect, useRef, useState } from 'react'
import MyTitle from '@/components/MyTitle'
import { PlusOutlined, EllipsisOutlined } from '@ant-design/icons'
import {
    ModalForm,
    ProForm,
    ProFormDateRangePicker,
    ProFormSelect,
    ProFormText,
    ProTable,
    TableDropdown
} from '@ant-design/pro-components'
import { Button, Form, message, Dropdown, Space, Tag } from 'antd'
import { ShowError, ShowMsg } from '@/utils/message'
import { Ajax } from '@/api/api'
import type { ActionType, ProColumns } from '@ant-design/pro-components'
import moment from 'moment'
import AddXuekeForm from './AddXuekeForm'
import DownLoad from '@/components/DownLoad'
import ExportExcle from '@/components/ExportExcle';
interface XuekeType {
    label: string;
    value: string;
}
type GithubIssueItem = {
    label: string,
    value: string,
    _id: string,
    time: Date,
}


const EduXueke: FC = () => {
    const [tableData, setTableData] = useState<any>([])
    const [open, setOpen] = useState<boolean>(false)
    const [flag, setFlag] = useState<boolean>(false)
    const [updateData, setUpdateData] = useState<any>({})

    const [form] = Form.useForm<XuekeType>();
    const actionRef = useRef<ActionType>()

    const downLoadData = () => {
        if (tableData.length > 0) {
            let fileName = "数据查询表"
            if (typeof window.navigator.msSaveBlob !== 'undefined') {
                window.navigator.msSaveBlob(new Blob([tableData],
                    { type: 'application/blog' }), fileName + '.xls')
            } else {
                let url = window.URL.createObjectURL(new Blob([tableData], { type: 'application/blog' }))
                let link = document.createElement('a')
                link.style.display = 'none'
                link.href = url
                link.setAttribute('download', fileName + '.xls')
                document.body.appendChild(link)
                link.click()
                document.body.removeChild(link);
                window.URL.revokeObjectURL(url);
            }
        } else {
            ShowMsg("表格暂无数据,不能导出下载")
        }
    }

    const columns: ProColumns<GithubIssueItem>[] = [{
        dataIndex: 'index',
        valueType: 'indexBorder',
        width: 48,
        title: '序号'
    },
    {
        title: "学科名称",
        dataIndex: 'label',
        copyable: true,
        ellipsis: true,
        tip: '学科名称过长会自动收缩',
        formItemProps: {
            rules: [
                {
                    required: true,
                    message: '此项为必填项',
                }
            ]
        }
    },
    {
        title: '学科编码',
        dataIndex: 'value',
        renderFormItem: (_, { defaultRender }) => {
            return defaultRender(_)
        },
        render: (_, record) => (
            <Space>
                {
                    <Tag color={'#123456'}>
                        {record.value}
                    </Tag>
                }
            </Space>
        )
    },
    {
        title: '添加日期',
        dataIndex: 'time',
        render: (_, item, index) => {
            return <span>{moment(item.time).format("yyyy-MM-DD HH:MM")}</span>
        },
        valueType: 'dateRange',
        hideInTable: false,
        search: false,
    },
    {
        title: '操作',
        valueType: 'option',
        key: 'option',
        render: (text, record, _, action) => [
            <Button size='small' type='ghost' key='ul' danger onClick={() => {
                setOpen(true)
                setFlag(true)
                setUpdateData(record)
            }}>修改2</Button>,

            <TableDropdown
                key="actionGroup"
                onSelect={async (key) => {
                    if (key == 'delete') {
                        let res = await Ajax.deletexueke({
                            _id: record._id
                        }) as any;
                        if (res.code == 200) {
                            action?.reload()
                        }
                    }
                    if (key == 'update') {

                    }
                }}
                menus={[
                    { key: 'update', name: '查看' },
                    { key: 'delete', name: '删除' },
                ]}
            />
        ]
    }
    ]

    useEffect(() => {

    }, [])
    return (
        <div>
            <MyTitle title='学科管理' />
            <Button type="primary" className='mt10' onClick={() => {
                setOpen(true)
                setFlag(false)
            }}>
                <PlusOutlined />添加学科
            </Button>
            <AddXuekeForm updateData={updateData} flag={flag} actionRef={actionRef} open={open} setOpen={setOpen}></AddXuekeForm>

            <div className="table-box mt10 ">
                <ProTable<GithubIssueItem>
                    columns={columns}
                    actionRef={actionRef}
                    cardBordered
                    request={async (params = {}, sort, filter) => {
                        console.log(params)
                        console.log(sort, filter);
                        let res = await Ajax.getxuekelist(params) as any;
                        setTableData(res.result)
                        if (res.code == 200) {
                            return {
                                data: res.result,
                                success: true
                            }
                        } else {
                            return {
                                data: res.result,
                                success: false
                            }
                        }

                    }}
                    editable={{
                        type: 'multiple',
                    }}
                    columnsState={{
                        persistenceKey: 'pro-table-singe-demos',
                        persistenceType: 'localStorage',
                        onChange(value) {
                            console.log('value: ', value);
                        },
                    }}
                    rowKey="_id"
                    search={{
                        labelWidth: 'auto',
                    }}
                    options={{
                        setting: {
                            listsHeight: 400,
                        },
                    }}
                    form={{
                        syncToUrl: (values, type) => {
                            if (type === 'get') {
                                return {
                                    ...values,
                                    created_at: [values.startTime, values.endTime],
                                };
                            }
                            return values;
                        },
                    }}
                    pagination={{
                        pageSize: 5,
                        onChange: (page) => console.log(page),
                    }}
                    dateFormatter="string"
                    headerTitle="学科列表"
                    toolBarRender={() => [

                        <ExportExcle data={tableData} columns={columns} fileNeme={"学科列表"} />
                        ,
                        <Dropdown
                            key="menu"
                            menu={{
                                items: [
                                    {
                                        label: '1st item',
                                        key: '1',
                                    },
                                    {
                                        label: '2nd item',
                                        key: '12',
                                    },
                                    {
                                        label: '3rd item',
                                        key: '13',
                                    },
                                ],
                            }}
                        >
                            <Button>
                                <EllipsisOutlined />
                            </Button>
                        </Dropdown>,
                    ]}
                />
            </div>
        </div>
    )
}

export default EduXueke